import React,{ memo, useEffect, useRef, useCallback, useState } from 'react'
import {useSelector,useDispatch,shallowEqual} from 'react-redux'

import {getTopBannerAction} from '../../store/actionCreators'

import { Carousel } from "antd";
import {
  BannerWrapper,
  BannerControl,
  BannerLeft,
  BannerRight
} from "./style";

export default memo(function ZZTopBanner() {

  const [currentIndex,setCurrentIndex] = useState(0)

  // 获取数据
  const {topBanners}=useSelector(state=>({
    // 使用redux-immutable的简化取值方法
    topBanners: state.getIn(["recommend","topBanners"])
    // 使用redux-immutable的取值方法
    // topBanners: state.get("recommend").get("topBanners")
    // 使用immutable的取值方法
    // topBanners: state.recommend.get("topBanners")
    // topBanners: state.recommend.topBanners
  }),shallowEqual)

  // 获取请求
  const dispatch = useDispatch();

  const bannerRef=useRef();

  useEffect(()=>{
    // 执行请求
    dispatch(getTopBannerAction())
  },[dispatch])

  // const { getBanners, topBanners }=props
  // useEffect(()=>{
  //   getBanners()
  // },[getBanners])

  const bannerChange=useCallback((from,to)=>{
    // console.log(to)
    setCurrentIndex(to)
  },[])

  const bgImage=topBanners[currentIndex] && (topBanners[currentIndex].imageUrl+"?imageView&blur=40x20")

  return (
    <BannerWrapper bgImage={bgImage}>
      <div className={'banner wrap-v2'}>
        <BannerLeft>
          <Carousel effect="fade" autoplay ref={bannerRef} beforeChange={bannerChange}>
            {
              topBanners.map((item,index) => {
                return (
                  <div className={'banner-item'} key={item.imageUrl}>
                    <img src={item.imageUrl} />
                  </div>
                )
              })
            }
          </Carousel>
        </BannerLeft>
        <BannerRight></BannerRight>
        <BannerControl>
          <button className={'btn left'} onClick={e=>bannerRef.current.prev()}></button>
          <button className={'btn right'} onClick={e=>bannerRef.current.next()}></button>
        </BannerControl>
      </div>
    </BannerWrapper>
  )
})
